import json
import time

import jwt
from django.db.models import Q
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.viewsets import ModelViewSet

from knight_api.models import *
from knight_api.page import *
from knight_api.serializers import *


# Create your views here.

# 菜单
class MenuView(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = MenuModel.objects.all().filter(pid=0)
    serializer_class = MenuSerializer


# 用户
class AdminView(ModelViewSet):
    queryset = AdminModel.objects.all()
    serializer_class = AdminSerializer
    pagination_class = LargeResultsSetPagination


# 角色
class RoleView(ModelViewSet):
    queryset = RoleModel.objects.all()
    serializer_class = RoleSerializer
    pagination_class = LargeResultsSetPagination


# 操作日志
class LoginMesView(ModelViewSet):
    queryset = LoginMesModel.objects.all()
    serializer_class = LoginMesSerializer
    filter_backends = [DjangoFilterBackend]
    filterset_fields = ['admin_id', 'is_login']
    pagination_class = LargeResultsSetPagination


# 会员管理
class MemberView(ModelViewSet):
    queryset = MemberModels.objects.all()
    serializer_class = MemberSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = '__all__'
    pagination_class = LargeResultsSetPagination
    ordering_fields = ['last_login_time', 'reg_time']


class PlatfromView(ModelViewSet):
    queryset = PlatfromModels.objects.all()
    serializer_class = PlatfromSerializer


# ###################### 简历管理

# 城市自关联
class CitycategoryView(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = Citycategory.objects.all().filter(pid=0)
    serializer_class = CitycategorySerializer


class CitycategoryView2(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = Citycategory.objects.all().filter(pid=0)
    serializer_class = CitycategorySerializer2


# 学历
class EductionView(ModelViewSet):
    queryset = Eduction.objects.all()
    serializer_class = EductionSerializer


# Jobcategory工作自关联
class JobcategoryView(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = Jobcategory.objects.all().filter(pid=0)
    serializer_class = JobcategorySerializer


class JobcategoryView2(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = Jobcategory.objects.all().filter(pid=0)
    serializer_class = JobcategorySerializer2


# 审核状态
class ResumeAuditView(ModelViewSet):
    queryset = ResumeAudit.objects.all()
    serializer_class = ResumeAuditSerializer


# 专业种类
class JobmajorsView(ModelViewSet):
    xx = serializers.PrimaryKeyRelatedField(read_only=True, many=True)
    queryset = Jobcategory.objects.all().filter(pid=0)
    serializer_class = JobmajorsSerializer


###########################职位管理
# 招聘信息 状态
class JobDisplayView(ModelViewSet):
    queryset = JobDisplay.objects.all()
    serializer_class = JobDisplaySerializer


# 公司福利
class JobTagView(ModelViewSet):
    queryset = JobTag.objects.all()
    serializer_class = JobTagSerializer


# 职位性质
class JobNatureView(ModelViewSet):
    queryset = JobNature.objects.all()
    serializer_class = JobNatureSerializer


# 工作经验

class ExperienceView(ModelViewSet):
    queryset = Experience.objects.all()
    serializer_class = ExperienceSerializer


# 公司信息表
class CompanyView(ModelViewSet):
    queryset = Company.objects.all()
    serializer_class = CompanySerializer


# 联系方式
class ContactView(ModelViewSet):
    queryset = Contact.objects.all()
    serializer_class = ContactSerializer


# 职位信息
class PositionInfoView(ModelViewSet):
    queryset = PositionInfo.objects.all()
    serializer_class = PositionInfoSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = '__all__'
    pagination_class = LargeResultsSetPagination
    ordering_fields = ['addtime', 'refreshtime']



# 广告位


# class Regin_fromView(ModelViewSet):
#     queryset = Regin_from.objects.all()
#     serializer_class = Regin_fromSerializers
#

class Regin_typeView(ModelViewSet):
    queryset = Regin_type.objects.all()
    serializer_class = Regin_typeSerializers

class Regin_ggView(ModelViewSet):
    queryset = Regin_gg.objects.all()
    serializer_class = Regin_ggSerializers
    pagination_class = LargeResultsSetPagination


# ###广告列表
class Gg_listView(ModelViewSet):
    queryset = ADlist.objects.all()
    serializer_class = Gg_listSerializers
    filter_backends = [DjangoFilterBackend, OrderingFilter]
    filterset_fields = '__all__'
    pagination_class = LargeResultsSetPagination

# 上传图片
def UpLoadInfo(request):
    if request.method == 'POST':
        # img = request.FILES.get('photo')
        # user = request.FILES.get('photo').name
        new_img = models.Avatar(
            photo=request.FILES.get('photo'),  # 拿到图片
            user=request.FILES.get('photo').name  # 拿到图片的名字
        )
        new_img.save()  # 保存图片
        return HttpResponse('上传成功！')

    # return render(request, 'upload.html')

### 退出登录效果
class Logout(View):

    def post(self, request):
        try:
            # 获取token值
            token = request.META.get("HTTP_AUTHORIZATION")

            AdminModel.objects.filter(token=token).update(
                expired_at=time.time() - 1)

            return JsonResponse({'code': 200, 'msg': "退出成功"})
        except Exception as e:
            return JsonResponse({'status': 'error', 'msg': '退出失败'})



## 登录

# class Login(View):
#
#     # def get(self, request):
#     #
#     #     list1 = Department.objects.filter().values()
#     #
#     #     listdata = getTree(list(list1), 0)
#     #
#     #     return JsonResponse({
#     #         'code': 200,
#     #         'data': listdata,
#     #     })
#
#     def post(self, request):
#         try:
#             body = json.loads(request.body)
#             username = body.get("username")
#             password = body.get("password")
#             # 判断用户名是否为空
#             if (len(username) <= 0 or len(password) <= 0):
#                 return JsonResponse({'status': "error", 'msg': "用户名和密码不能为空"})
#             print("123123用户名不为空")
#
#             # 查询用户是否存在，如果不存在提示错误信息
#
#             user = AdminModel.objects.filter(username=username).first()
#             print(user.password, 123)
#
#             if (not user):
#
#                 return JsonResponse({'status': "error", 'msg': "用户名不存在"})
#
#             else:
#                 # 密码是否一致
#                 print('接下来判断密码是否一致')
#                 print(user.password, "后台的密码")
#                 if (user.password != password):
#                     return JsonResponse({'status': 'error', 'msg': "密码错误"})
#                 else:
#
#                     # 登录成功生成token值，更新token值
#                     dict = {"name": user.username, "password": user.password}
#                     # 使用jwt生成token
#                     token = jwt.encode(dict, "login_token", algorithm="HS256")
#
#                     print(token, '这是token111111111111111111')
#                     # 更新token到用户表中去，生成token的信息内容
#                     AdminModel.objects.filter(id=user.id).update(
#                         token=token, expired_at=time.time() + 7200)
#
#                     roles = RoleModel.objects.filter(id=user.role_id).all().values()  # 查询角色的信息
#                     role = roles.first().get('name')
#                     print(roles.first().get('name'), '角色信息')
#                     return JsonResponse({
#                         'status': 'ok',
#                         'type': 'account',
#                         'currentAuthority': 'admin',
#                         # 返回用户的基本信息
#                         'data': {
#                             'id': user.id,
#                             'username': user.username,
#                             'token': token,
#                             'role': role,
#                         }
#                     })
#
#         except Exception:
#             return JsonResponse({'status': "error", 'msg': "登录失败"})

class Info(View):
    def get(self,request):
        token = request.META.get("HTTP_AUTHORIZATION").split(" ")[1]
        data = list(AdminModel.objects.filter(token=token).values())
        print('*'*50)
        print(data[0])
        obj = {}
        obj1 = {}
        obj["name"] = data[0]["username"]
        obj["avatar"] = "https://gimg2.baidu.com/image_search/src=http%3A%2F%2F5b0988e595225.cdn.sohucs.com%2Fa_auto%2Cc_zoom%2Cw_640%2Cq_70%2Fimages%2F20180808%2F95fc5a2112fb43f283112e01dd1d34ad.jpeg&refer=http%3A%2F%2F5b0988e595225.cdn.sohucs.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1672909324&t=073837b55d1fa00202055c4ff7d7dbe8"
        obj["roles"] = "我是角色"
        obj1["code"] = 200
        obj1["info"] = obj
        return JsonResponse(obj1, safe=False)

class Login(View):
    def get(self,request):
        return JsonResponse({"msg":"快去登录不然没数据哦！"},safe=False)
    def post(self,request):
        user = AdminModel.objects.all().values()
        print(list(user))
#         获取body数据
        req_body = json.loads(request.body.decode())
        print(req_body["username"])
        # try:
        #     res = user.filter(username=req_body["username"])
        #     if res == '':
        #
        try:
            useinfo = user.filter(username=req_body["username"])
            if not useinfo:
                return JsonResponse({"state": 201, "message": "用户不存在"})
            res = user.filter(Q(username=req_body["username"]) & Q(password=req_body["password"]))
        except Exception:
            return JsonResponse({"state": 403, "message": "用户或密码错误"})
        if not res:
            return JsonResponse({"state": 201, "message": "密码错误"})
        info = {
            'exp': time.time() + 9000000000,

            'iat': time.time(),

            'iss': 'Issuer',

            'data':{
                'username':req_body["username"],
                'timestamp':time.time()
            }

        }

        jwt_encode = jwt.encode(info,request.body,algorithm="HS256")
        AdminModel.objects.filter(username=req_body["username"]).update(
            token=jwt_encode,avatar=info["exp"]
        )
        result_user = AdminModel.objects.get(username=req_body["username"])
        return JsonResponse({"currentuser":result_user.username,"token":result_user.token
                             ,"message":"登录成功","code":200
                             })
        # return JsonResponse({'123':'1234'},safe=False)

class CurrentUser(View):

    def get(self, request):
        # 获取token值,通过token获取用户详情的基本信息内容
        print(1111111111111111111111111111111111111111111111111111111111111)
        token = request.META.get("HTTP_AUTHORIZATION")
        print(token)
        user = AdminModel.objects.filter(token=token).first()

        # roles = user.roles.filter().first()

        return JsonResponse({
            'success': True,
            'data': {
                "name": user.username,
                "avatar": user.profile_picture,
                'id': user.id,
                # "access": roles.role_name,
                # 'code': roles.role_code,
            }
        })
